﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;
using SixLabors.Fonts;
using SkiaSharp.QrCode.Image;
using SkiaSharp;
using QRCoder;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace MangoMes.Write.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class QRcodersController : ControllerBase
    {

        private readonly IWebHostEnvironment host;

        public QRcodersController(IWebHostEnvironment host)
        {
            this.host = host;
        }

        [HttpGet]
        public async Task<string> GETThey()
        {
            //创建一个新的QRCodeGenerator实例
            QRCodeGenerator qrGenerator = new QRCodeGenerator();
            //创建一个二维码 “123123”为显示内容
            var abc = "http://localhost:64980/QUCode/QUCodeSearch";
            QRCodeData qrCodeData = qrGenerator.CreateQrCode(abc, QRCodeGenerator.ECCLevel.M, true);
            //放入生成的二维码
            QRCode qrCode = new QRCode(qrCodeData);
            //获取到二维码图形
            Bitmap qrCodeImage = qrCode.GetGraphic(15, Color.Black, Color.White, false); 
            Bitmap newBM = new Bitmap(550 + 60, 550 + (35 * 2) + 60);
            //新画布
            Graphics newGP = Graphics.FromImage(newBM);
            //清除所有背景色并指定背景颜色
            newGP.Clear(Color.White);
            // 插值算法的质量
            newGP.InterpolationMode = InterpolationMode.HighQualityBicubic;
   
            newGP.DrawImage(qrCodeImage, new Rectangle(30, 30, 550, 550), new Rectangle(0, 0, qrCodeImage.Width, qrCodeImage.Height), GraphicsUnit.Pixel);
            //设置字体
      
            //RectangleF rec = new RectangleF((float)(newBM.Width * 0.10), newBM.Height - ((35 * 2) + 15), (float)(newBM.Width * 0.80), font.Height * 2);
            Brush fontBrush = SystemBrushes.ControlText;
            //此处为设置居中方式可以让换行后的文字也居中
            StringFormat sformat = new StringFormat();
            sformat.Alignment = StringAlignment.Center;
            sformat.LineAlignment = StringAlignment.Center;
            //newGP.DrawString("嗷嗷待食发货时肯定会房间卡是放假卡上的合肥师范", font, fontBrush, rec, sformat);
            //资源释放
            newGP.Dispose();

            //文件wwwroot路径
            var imaegslu = @"Router";
            //host 是个引用需要实例化
            //他是用于写入我们的vs图片路径
            var fulldir = Path.Combine(host.WebRootPath, imaegslu);
            //
            if (!Directory.Exists(fulldir))
            {
                //放入
                Directory.CreateDirectory(fulldir);
            }
            var filename = $"{DateTime.Now.ToString("yyyyMMddhhss")}.jpg";

            //刷入
            var path = Path.Combine(fulldir, filename);
            newBM.Save(path);
            return $"{imaegslu}/{filename}";
        }
    }
}
